<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="850px">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
      :inline="true"
    >
      <el-form-item label="老人姓名" prop="elderId">
        <el-input v-model="formData.elderName" disabled class="mr-1" />
        <el-button @click="clickChooseElder">选择老人</el-button>
      </el-form-item>
      <el-form-item label="缴存方式" prop="medicineDepositType">
        <el-select
          v-model="formData.medicineDepositType"
          placeholder="请输入缴存方式"
          :clearable="true"
        >
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.HEALTH_MEDICINE_DEPOSIT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddMedicine">添加药品</el-button>
      <el-button @click="clickDeleteMedicine">删除药品</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="HealthMedicineDepositEdit"
      @row-click="handleRowClick"
    >
      <template #medicineType="{ row }">
        {{ getDictObj(DICT_TYPE.HEALTH_MEDICINE_TYPE, row['medicine.medicineType']).label }}
      </template>
      <template #medicineDosageForm="{ row }">
        {{
          getDictObj(DICT_TYPE.HEALTH_MEDICINE_DOSAGE_FORM, row['medicine.medicineDosageForm'])
            .label
        }}
      </template>
      <template #number="{ row }">
        <InputNumber v-model="row.number" class="!w-100px" type="decimal" />
      </template>
      <template #expireDate="{ row }">
        <el-date-picker
          v-model="row.expireDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 130px !important"
        />
      </template>
    </Table>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <HealthMedicineSelect ref="healthMedicineSelectRef" @select-value="handleSelectHealthMedicine" />
  <ElderInfoSelect ref="elderInfoSelectRef" @row-dblclick="handleSelectElderInfo" />
</template>
<script setup name="HealthMedicineDepositEdit" lang="ts">
import HealthMedicineSelect from '../healthMedicine/HealthMedicineSelect.vue'
import ElderInfoSelect from '@/views/elder/elderInfo/ElderInfoSelect.vue'
import * as HealthMedicineDepositModel from '@/model/health/medicine/HealthMedicineDeposit'
import * as HealthMedicineDepositApi from '@/api/health/medicineDeposit'
import { DICT_TYPE, getDictObj, getDictOptions } from '@/utils/dict'
import InputNumber from '@/components/InputNumber/src/InputNumber.vue'

interface HealthMedicineDepositEdit extends HealthMedicineDepositModel.HealthMedicineDeposit {
  'medicine.medicineName': string
  'medicine.medicineBrevityCode': string
  'medicine.medicineType': string
  'medicine.medicineSpecification': string
  'medicine.medicineDosageForm': string
}
interface MaterialInventoryEdit {
  elderName: string
  elderId: number | undefined
  medicineDepositType: number
  details: HealthMedicineDepositEdit[]
}
const { t } = useI18n()
const message = useMessage()
const healthMedicineSelectRef = ref()
const elderInfoSelectRef = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<MaterialInventoryEdit>({
  elderId: undefined,
  elderName: '',
  medicineDepositType: 1,
  details: []
})
const formRules = reactive({
  elderName: [{ required: true, message: '老人不能为空', trigger: 'blur' }],
  medicineDepositType: [{ required: true, message: '缴存方式不能为空', trigger: 'blur' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '药品名称',
    prop: 'medicine.medicineName'
  },
  {
    label: '药品简码',
    prop: 'medicine.medicineBrevityCode'
  },
  {
    label: '药品类型',
    prop: 'medicine.medicineType',
    slot: 'medicineType'
  },
  {
    label: '药品规格',
    prop: 'medicine.medicineSpecification'
  },
  {
    label: '药品剂型',
    prop: 'medicine.medicineDosageForm',
    slot: 'medicineDosageForm'
  },
  {
    label: '数量',
    prop: 'number',
    slot: 'number',
    minWidth: '100'
  },
  {
    label: '有效期',
    prop: 'expireDate',
    slot: 'expireDate',
    minWidth: '130'
  }
]
/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    elderId: undefined,
    elderName: '',
    medicineDepositType: 1,
    details: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.details.length <= 0) {
    message.alert('请选择药品')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data: HealthMedicineDepositModel.HealthMedicineDeposit[] = []
    formData.value.details.forEach((detail) => {
      data.push({
        id: undefined,
        elderId: formData.value.elderId,
        medicineDepositType: formData.value.medicineDepositType,
        medicineId: detail.medicineId,
        number: detail.number,
        expireDate: detail.expireDate
      })
    })
    await HealthMedicineDepositApi.create(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
  emit('success')
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

/** 单击删除药品 */
const clickDeleteMedicine = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的药品')
    return
  }
  const index = formData.value.details.indexOf(tableCurrentRow.value)
  formData.value.details.splice(index, 1)
}

/** 单击新增药品 */
const clickAddMedicine = () => {
  healthMedicineSelectRef.value.open()
}

const clickChooseElder = () => {
  elderInfoSelectRef.value.open()
}

const handleSelectHealthMedicine = (selectMaterialStockList) => {
  selectMaterialStockList.forEach((element) => {
    const detail = {
      id: undefined,
      elderId: undefined,
      medicineDepositType: 1,
      medicineId: element.id,
      expireDate: undefined,
      number: 1,
      'medicine.medicineName': element.medicineName,
      'medicine.medicineBrevityCode': element.medicineBrevityCode,
      'medicine.medicineType': element.medicineType,
      'medicine.medicineSpecification': element.medicineSpecification,
      'medicine.medicineDosageForm': element.medicineDosageForm
    }
    formData.value.details.push(detail)
  })
}

const handleSelectElderInfo = (selectElderInfo) => {
  formData.value.elderName = selectElderInfo.name
  formData.value.elderId = selectElderInfo.id
}
</script>
